#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/02/12
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

import subprocess
import os
from json import dumps
from flask import jsonify, session
from flasky.common import AxiosMessage
from flasky.model import AppInfo, Role, User, Cashier
from flasky.device import Ethernet


class AxiosManager(AxiosMessage):
    # 接口消息管理器
    def __init__(self) -> None:
        super().__init__()
        self.Ethernet = Ethernet("ens33")
        self.network = dict.fromkeys(('EthName', 'Mac', 'Address', 'Gateway', 'DNS', 'State'))
        self.log_path = "logs"

    def log_views_page_data(self, page=1):
        """
        日志预览功能
        """
        log_file = session.get("LogFile")
        if not log_file:
            log_file = "app.log"
        logs = [i for i in os.listdir(self.log_path) if not i.startswith(".")]
        with open(f"{self.log_path}/{log_file}", mode="r", encoding="utf8") as f:
            log_info = f.readlines()
        log_info.reverse()
        # 获取页数
        pages = round(len(log_info) / 100)
        page_iters = list(range(pages+1))
        page_iters.remove(0)
        if page == 1:
            page_info = log_info[:100]
            if pages <= 1:
                page_iters = [1,]
        else:
            start = page * 100
            end = (page+1) * 100
            page_info = log_info[start:end]
        
        return {'log_file': log_file, 'logs': logs, 'page_info': page_info, 'pages': page_iters, 'current_page': page}
        
    def users_page_data(self):
        """
        用户管理页面数据
        """
        # 筛选条件
        users_filters = session.get('UsersFilter')
        if not users_filters:
            users_filters = dict.fromkeys(("LoginName", "UserName", "RoleID", "CashierName"))
        filters = User.generate_filters(**users_filters)
        users = User.query.filter(*filters).all()
        # 数据
        roles = Role.query.all()
        cashiers = Cashier.query.all()
        column_name = User.columns_name()
        return {
            "ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), 
            'Roles': roles, 'Cashiers': cashiers, 'Users': users, 'UsersFilter': dumps(users_filters,ensure_ascii=False)}
        
    def network_page_data(self):
        """
        网络设置页面数据
        """
        self.Ethernet.get_conn_state()
        network_info = self.Ethernet.__dict__.copy()
        column_name = self.Ethernet.column_names()
        return {"ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False), 'NetworkInfo': network_info}

    def app_info_page_data(self):
        """
        返回系统信息
        """
        column_name = AppInfo.columns_name()
        return {"ColumnName":column_name, "ColumnNameJSON": dumps(column_name,ensure_ascii=False)}

    def __reset_filters(self, view):
        """
        清除筛选器
        """
        if view == "users":
            filters = session.get("UsersFilter")
            if filters:
                del session['UsersFilter']
            return "OK"

    def __set_filters(self, view, filters):
        """
        设置筛选器
        """
        if view == "users":
            session['UsersFilter'] = filters
            return self.success("數據查詢中，請稍候。")
        elif view == "logs":
            session['LogFile'] = filters
            return 'OK'

    def __select_data(self, view, condition):
        """
        选择数据
        """
        if view == "users":
            r = User.query.filter_by(id=condition).first()
            return jsonify(**r.to_dict())

    def __modify_data(self, view, data):
        """
        系统信息更新
        """
        if view == "setting":
            if AppInfo.modify_data(**data) is True:
                return self.success("系統信息更新成功！")
            return self.warning("系統信息更新失敗！")
        elif view == 'network':
            ret = self.Ethernet.update_network_info(**data)
            if ret == 'success':
                return self.success("網絡更新成功，請重新登陸系統")
            elif ret == 'error':
                return self.error("網絡更新錯誤！")
            elif  ret == 'exists':
                return self.warning("網絡沒有更改！")

    def __delete_data(self, view, data):
        """
        删除数据
        """
        if view == "users":
            ret = User.delete_user(**data)
            if ret:
                return self.success(f"刪除用戶{ret}成功")
            return self.warning(f"刪除用戶失敗！")

    def __add_data(self, view, data):
        """
        新增数据
        """
        if view == "users":
            ret = User.add_user(**data)
            if ret:
                return self.success(f"添加用戶{ret}成功")
            return self.warning("添加用戶失敗！")

    def messages(self, **kwargs):
        """
        消息处理
        """
        view = kwargs.get('View')
        for k, v in kwargs.items():
            if k == "Add":
                return self.__add_data(view, v)
            elif k == "Delete":
                return self.__delete_data(view, v)
            elif k == "Update":
                return self.__modify_data(view, v)
            elif k == "GetData":
                return self.__select_data(view, v)
            elif k == "SetFilter":
                return self.__set_filters(view, v)
            elif k =="ResetFilter":
                return self.__reset_filters(view)
        return self.error("參數錯誤，系統無法響應！請聯係管理員")
        
                    

